<template>
    <view>
        <web-view :webview-styles="webviewStyles" :src="url" @message="message"></web-view>
    </view>
</template>

<script>
	export default {
		components: {
		},
		data() {
			return {
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				url: '',
			}
		},
		onLoad(options) {
			// #ifdef APP-PLUS
			   plus.screen.lockOrientation('default');
			// #endif
			console.log(options);
			this.url = options.url;
			uni.setNavigationBarTitle({
				title: options.title
			})
		},
		onUnload() {
			// #ifdef APP-PLUS
			   plus.screen.lockOrientation('portrait-primary');
			// #endif
		},
		methods: {
			message(event) {
				//{"type":"message","target":{},"currentTarget":{},"timeStamp":1668765112716,"detail":{"data":[{"action":"message"}]}}
				if(event.detail.data[0].action==='requestPayment'){
					console.log('当字段为success的时候，跳转页面')
					this.requestPayment(event.detail.data[0].data)
				}
			},
			
			requestPayment(res) {
				console.log('requestPayment')
				console.log(res)
				console.log(res.nonceStr)
				const orderInfo = {
					appid: res.appId,
					noncestr: res.nonceStr,
					package: res.packageValue,
					partnerid: res.partnerId,
					prepayid: res.prepayId,
					timestamp: res.timeStamp,
					sign: res.sign,
				}
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: orderInfo,
					success: (e) => { 
						this.sendMsgToWebview();
					},
					fail: (e) => {
						uni.showToast({
							title: e.errMsg
						})
						console.log("fail", e);
						if(e.errMsg.indexOf('denied')>-1){ 
							uni.showModal({
								content: '该小程序暂未开通支付功能',
								showCancel: false
							})
						}else{
							uni.showModal({
								content: "APP支付失败,原因为: " + e.errMsg,
								showCancel: false
							})
						}
					}
				})
			},
			
			sendMsgToWebview() {
				let _funName='msgFromUniapp'
				let _data = {
				    msg:'refresh'
				}
				let currentWebview = this.$scope.$getAppWebview().children()[0];
				currentWebview.evalJS(`${_funName}(${JSON.stringify(_data)})`)
			},
		}
	}
</script>

<style>

</style>
